package com.baize.filedowndemo.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

public class FileUtil {
  public static final long KB = 1024;
  public static final long MB = 1024 * 1024;
  public static SimpleDateFormat Y4M2D2 = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm");
  public static final String DEFAULT_FILE_IMAGE_POSTFIX = ".png";
  public static final String DEFAULT_FILE_VIDEO_POSTFIX = ".mp4";

  public static boolean deleteFile(String url) {
    boolean result = false;
    File file = new File(url);
    if (file.exists()) {
      try {
        result = file.delete();
      } catch (Exception e) {
      }
    }
    return result;
  }

  public static String getImageFilePostfix(String fileName) {
    int p = fileName.lastIndexOf(".");
    if (p > 0) {
      return fileName.substring(p);
    }

    return DEFAULT_FILE_IMAGE_POSTFIX;
  }

  public static String getVideoFilePostfix(String fileName) {
    int p = fileName.lastIndexOf(".");
    if (p > 0) {
      return fileName.substring(p);
    }

    return DEFAULT_FILE_VIDEO_POSTFIX;
  }

  public static String readFile(InputStream is) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte buf[] = new byte[1024];
    int len;
    try {
      while ((len = is.read(buf)) != -1) {
        outputStream.write(buf, 0, len);
      }
    } catch (IOException e) {
    } finally {
      try {
        outputStream.close();
      } catch (IOException e) {
      }
      try {
        is.close();
      } catch (IOException e) {
      }
    }
    return outputStream.toString();
  }

  public static long getFileSize(String path) {
    try {
      File f = new File(path);
      return f.length();
    } catch (Exception e) {
    }
    return 0L;
  }

  public static boolean limitFileSize(String path, long size) {
    File f = new File(path);
    if (!f.exists()) return false;
    return f.length() < size;
  }

  public static void removeDir(File dir) {
    if (dir == null || !dir.exists() || !dir.isDirectory())
      return;
    for (File file : dir.listFiles()) {
      if (file.isFile()) {
        file.delete();
      } else {
        removeDir(file);
      }
    }
    dir.delete();// 删除目录本身
  }

  //判断文件是否存在
  public static boolean fileIsExists(String strFile) {
    try {
      File f = new File(strFile);
      if (!f.exists()) {
        return false;
      }

    } catch (Exception e) {
      return false;
    }

    return true;
  }

}
